import { ref } from 'vue';

export const videInfo = ref([
    {
        team: 'red_V1.0',
        url: 'http://1.95.36.193:3000/video/red.mp4',
        txt: '',
        isLoadSuccess: false,
        indexDB_URL: null,
        speed: 0
    },
    {
        team: 'blue_V1.0',
        url: 'http://1.95.36.193:3000/video/blue.mp4',
        txt: '',
        isLoadSuccess: false,
        indexDB_URL: null,
        speed: 0
    },
])

export const initSettlementScreen = () => {
    const request = indexedDB.open('VideoDatabase', 1);

    request.onupgradeneeded = (event) => {
        const db = event.target.result;
        if (!db.objectStoreNames.contains('videos')) {
            db.createObjectStore('videos', { keyPath: 'id' });
            console.log('对象存储 "videos" 已创建');
        }
    };

    request.onsuccess = (event) => {
        videInfo.value.forEach(async item => {
            if (!await checkKeyExistsInIndexedDB(item.team)) {
                saveVideoToIndexedDB(item);
            }
            else {
                loadVideoFromIndexedDB(item);
            }
        })
    };
}


export const checkKeyExistsInIndexedDB = (key) => {
    return new Promise((resolve, reject) => {
        const request = indexedDB.open('VideoDatabase', 1);

        request.onsuccess = (event) => {
            const db = event.target.result;
            const transaction = db.transaction('videos', 'readonly');
            const store = transaction.objectStore('videos');

            const getRequest = store.get(key);

            getRequest.onsuccess = (event) => {
                const result = event.target.result;
                if (result) {
                    resolve(true); // 键存在
                } else {
                    resolve(false); // 键不存在
                }
            };

            getRequest.onerror = (event) => {
                reject(`检查键是否存在时出错: ${event.target.error}`);
            };
        };

        request.onerror = (event) => {
            reject(`打开 IndexedDB 数据库失败: ${event.target.error}`);
        };
    });
};


export const saveVideoToIndexedDB = async (data) => {
    try {
        const response = await fetch(data.url)
        const contentLength = response.headers.get('Content-Length');
        if (!contentLength) {
            console.warn('无法获取视频的总大小');
            return;
        }

        console.log('正在下载视频');
        const totalSize = parseInt(contentLength, 10); // 总大小
        let loadedSize = 0;                            // 已下载大小
        const reader = response.body.getReader();
        const chunks = [];
        let lastTime = Date.now();                     // 上一次计算时间
        let lastLoadedSize = 0;                        // 上一次已下载大小

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            loadedSize += value.length;
            chunks.push(value);

            // 计算实时网速
            const currentTime = Date.now();
            const elapsedTime = (currentTime - lastTime) / 1000; // 时间间隔（秒）
            if (elapsedTime >= 1) { // 每秒更新一次网速
                data.speed = ((loadedSize - lastLoadedSize) / elapsedTime) / 1024; // KB/s
                lastTime = currentTime;
                lastLoadedSize = loadedSize;
            }

            // 更新下载进度
            data.txt = `${data.team} 结算画面，下载进度: ${((loadedSize / totalSize) * 100).toFixed(2)}%，下载速度: ${((loadedSize / totalSize) * 100).toFixed(2) >= 100 ? 0 : data.speed.toFixed(2)} KB/s`;
        }

        const videoBlob = new Blob(chunks);
        const request = indexedDB.open('VideoDatabase', 1);

        request.onsuccess = (event) => {
            const db = event.target.result;
            const transaction = db.transaction('videos', 'readwrite');
            const store = transaction.objectStore('videos');

            // 保存视频到数据库
            store.put({ id: data.team, blob: videoBlob });
            console.log(`${data.team} 视频已保存到 IndexedDB`);
            loadVideoFromIndexedDB(data);
        };

        request.onerror = (event) => {
            console.error('IndexedDB 打开失败:', event.target.error);
        };
    } catch (error) {
        console.error('保存视频到 IndexedDB 时出错:', error);
    }
};


// 加载视频
export const loadVideoFromIndexedDB = (data) => {
    const request = indexedDB.open('VideoDatabase', 1);

    request.onsuccess = (event) => {
        const db = event.target.result;
        const transaction = db.transaction('videos', 'readonly');
        const store = transaction.objectStore('videos');

        const getRequest = store.get(data.team);

        getRequest.onsuccess = (event) => {
            const videoData = event.target.result;
            if (videoData) {
                data.indexDB_URL = URL.createObjectURL(videoData.blob);
                data.isLoadSuccess = true;
                console.log(`${ data.team }队，视频已从 IndexedDB 加载`, data.indexDB_URL);
            } else {
                console.warn(`${ data.team }队，未找到视频数据，现在开始加载`);
            }
        };
        getRequest.onerror = (event) => {
            console.error(`IndexedDB 数据库错误:`, event.target.error);
        };
    };
};


export const deleteVideoFromIndexedDB = (id) => {
    const request = indexedDB.open('VideoDatabase', 1);

    request.onsuccess = (event) => {
        const db = event.target.result;
        const transaction = db.transaction('videos', 'readwrite');
        const store = transaction.objectStore('videos');

        // 删除指定 ID 的视频
        const deleteRequest = store.delete(id);

        deleteRequest.onsuccess = () => {
            console.log(`视频 ${id} 已从 IndexedDB 删除`);
        };

        deleteRequest.onerror = (event) => {
            console.error('删除视频失败:', event.target.error);
        };
    };

    request.onerror = (event) => {
        console.error('IndexedDB 打开失败:', event.target.error);
    };
};


export const clearVideosFromIndexedDB = () => {
    const request = indexedDB.open('VideoDatabase', 1);

    request.onsuccess = (event) => {
        const db = event.target.result;
        const transaction = db.transaction('videos', 'readwrite');
        const store = transaction.objectStore('videos');

        // 清空对象存储
        const clearRequest = store.clear();

        clearRequest.onsuccess = () => {
            console.log('所有视频已从 IndexedDB 清空');
        };

        clearRequest.onerror = (event) => {
            console.error('清空视频失败:', event.target.error);
        };
    };

    request.onerror = (event) => {
        console.error('IndexedDB 打开失败:', event.target.error);
    };
};


export const deleteIndexedDB = () => {
    const deleteRequest = indexedDB.deleteDatabase('VideoDatabase');

    deleteRequest.onsuccess = () => {
        console.log('IndexedDB 数据库已删除');
    };

    deleteRequest.onerror = (event) => {
        console.error('删除 IndexedDB 数据库失败:', event.target.error);
    };

    deleteRequest.onblocked = () => {
        console.warn('删除操作被阻止，请关闭所有使用该数据库的页面');
    };
};